﻿using System;
using System.Data;
using System.Data.SqlClient;
using Koonsoft.HYCRM.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Koonsoft.HYCRM.DAL
{
    /// <summary>
    /// 动态密码访问
    /// </summary>
    public class OTPDAL
    {
        private static readonly Database Database = DatabaseFactory.CreateDatabase("KOONCRMDB");

        /// <summary>
        /// 根据条形码获取动态密码对象
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static OTPInfo GetOTPInfoByBarcode(string barcode)
        {
            const string sql = @"select * from otp where Barcode=@barcode";

            using(var cmd = Database.GetSqlStringCommand(sql))
            {
                Database.AddInParameter(cmd, "@barcode",DbType.String,barcode);

                var rd = (RefCountingDataReader)Database.ExecuteReader(cmd);

                var sqlrd = (SqlDataReader) rd.InnerReader;
                
                if(sqlrd.HasRows)
                {
                    sqlrd.Read();
                    return new OTPInfo
                               {
                                   Authkey = sqlrd["authkey"].ToString(),
                                   Barcode = barcode,
                                   Currdft = Convert.ToInt32(sqlrd["currdft"]),
                                   Currsucc = Convert.ToUInt64(sqlrd["currsucc"])
                               };
                }
            }

            return null;
        }

        /// <summary>
        /// 更新漂移值与成功值
        /// </summary>
        /// <param name="currsucc"></param>
        /// <param name="currdft"></param>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public static bool UpdateOTPInfo(UInt64 currsucc,int currdft,string barcode)
        {
            const string sql = @"update otp set Currdft=@currdft,Currsucc=@currsucc where Barcode=@barcode";

            using (var cmd = Database.GetSqlStringCommand(sql))
            {
                Database.AddInParameter(cmd, "@currdft", DbType.Int32, currdft);
                // 不得已转换
                Database.AddInParameter(cmd, "@currsucc", DbType.Int64, currsucc);
                Database.AddInParameter(cmd, "@barcode", DbType.String, barcode);

                return Database.ExecuteNonQuery(cmd) == 1;
            }
        }


    }
}
